import {defineStore, storeToRefs} from "pinia";
import dayjs from "@/utils/dayjs";
import { useUserStore} from "@/store/module/user";


export const useAdminStore = defineStore('admin', {
    persist: true, //使用持久化插件
    state: () => {   //是一个函数，返回一个对象，用于存储状态
        return {
            postRecentList: {} as IPostRecentList,

        }
    },
    getters: {
        curUserPostRecentList(): IPostRecentItem[] {
            const {userInfo, isLogin} = storeToRefs(useUserStore())
            if (isLogin.value) {
                window.$message.error('未登录')
                return []
            }
            return this.postRecentList[userInfo.value.username] as IPostRecentItem[]|| []
        }
    },  //用于存储计算属性
    actions: {  //用于封装业务逻辑
        removePostRecentItem(id: any) {
            const {userInfo, isLogin} = storeToRefs(useUserStore())
            if (isLogin.value) {
                window.$message.error('未登录')
                return
            }
            let key = userInfo.value.username
            if (!this.postRecentList[key]) {
                this.postRecentList[key] = []
            }
            const index = this.postRecentList[key].findIndex((value: IPostRecentItem) => value.id === id);
            if (index !== -1) {
                this.postRecentList[key].splice(index, 1);
            }
        },
        clearUserPostRecentList() {
            const {userInfo, isLogin} = storeToRefs(useUserStore())
            if (isLogin.value) {
                window.$message.error('未登录')
                return
            }
            let key = userInfo.value.username
            this.postRecentList[key] = []
        },
        openPost(item: IPost,operateType:string) {
            const {userInfo, isLogin} = storeToRefs(useUserStore())
            if (isLogin.value) {
                window.$message.error('未登录')
                return
            }
            let key = userInfo.value.username
            if (!this.postRecentList[key]) {
                this.postRecentList[key] = []
            }
            const index = this.postRecentList[key].findIndex((value: IPostRecentItem) => value.id === item.id);
            if (index !== -1) {
                this.postRecentList[key].splice(index, 1);
            }
            this.postRecentList[key].unshift({
                id: item.id,
                title: item.title,
                cover: item.cover,
                tags: item.tags,
                username: item.username,
                comments: item.comments,
                views: item.views,
                createdAt: item.createdAt,
                updatedAt: item.updatedAt,
                operateTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
                operateType:operateType,
            } as IPostRecentItem)
        },

    },
})